#!/usr/bin/env python

import sys
sys.path += ['/home/boincadm/projects/alpha/bin']

import SocketServer
import time

import boinc_path_config
from Boinc import database, boinc_db, configxml

def get_work():
    appname = "pymw"
    app = database.Apps.find1(name=appname)
    wus = database.Workunits.find(app=app)
    return wus

class MyTCPHandler(SocketServer.BaseRequestHandler):
    """
    The RequestHandler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        #self.data = self.request.recv(1024).strip()
        #print "%s wrote:" % self.client_address[0]
        #print self.data
        # just send back the same data, but upper-cased
        while 1:
            database.connect()
            wus = get_work()

            for wu in wus:
                #try:
                time.sleep(0.01)
                rec = "0 %d %s" % (wu.id, wu.batch)
                results = database.Results.find(workunit=wu)
                if wu.error_mask != 0:
                    rec += " 2" #failed
                elif wu.canonical_result:
                    rec += " 1" # success
                elif len(results) == 0:
                    rec += " 0" # pending
                else:
                    rec += " 3" # running
                #for r in results:
                #    if r.
                #    self.request.send(" " + str(r.host.id))
                self.request.send(rec + "\n")
                #except:
                #    self.request.send("end")
            database.close()
        self.request.send("end")
        
        
if __name__ == "__main__":
    HOST, PORT = "localhost", 9999

    # Create the server, binding to localhost on port 9999
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()
    